/**
 * 邮件模板新增编辑页
 */
import React, { useEffect, useRef, useState } from 'react';
import { Form, Card, Button, Input, message, Spin } from 'antd';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import pageTabUtil from '@/utils/pageTabUtil';
import { useRequest, defaultFormatResult } from '@/hooks';
import { BottomAction } from '@/components';
import FileUpload from '@/components/Custom/FileUpload';
import { fetchCompany } from '@/containers/service';
import { BraftTemplate, CompanySelect } from './containers';
import { transformFileList } from '../utils';
import {
    getNoticeTemplate,
    addNoticeTemplate,
    updateNoticeTemplate,
    getUsedOrgList,
    getNoticeTemplateDefaultContent
} from './service';
import { TEMPLATE_TYPE, TEMPLATE_TITLE } from './constants';
import styles from './index.less';

const NoticeTemplateEdit = ({ form, location }) => {
    const { query } = location;
    const { getFieldDecorator } = form;
    const [editorValue, setEditorValue] = React.useState('');
    const [defaultTemplateValue, setDefaultTemplateValue] = React.useState(''); // 默认模板
    const [flag, setFlag] = React.useState(false);

    const isAddPage = React.useMemo(() => {
        const { pathname = '' } = location;
        return pathname.toLowerCase().includes('add');
    }, [location]);
    const isOfferInfo = React.useMemo(() => [TEMPLATE_TYPE.OFFER_INFO].includes(query?.type), []);
    const contentTittle = React.useMemo(() => (isOfferInfo ? '内容' : '邮件正文'), []);
    const { data: orgList, loading: orgLoading, run: fetchOrgList } = useRequest(
        () =>
            fetchCompany({
                // organizationPermissions: 1,
                showTreeFlag: 0
            }),
        {
            manual: true,
            ...defaultFormatResult
        }
    );

    const gradeMap = React.useMemo(() => {
        if (!orgList) {
            return {};
        }
        const obj = {};
        orgList.forEach(item => {
            obj[item.organizationCode] = item;
        });
        return obj;
    }, [orgList]);

    const { data: usedList, loading: usedLoading, run: fetchUsedList } = useRequest(() => getUsedOrgList(query?.type), {
        manual: true,
        initialData: [],
        formatResult: res => {
            if (res) {
                const { code, data, msg } = res;
                if (code === 10000) {
                    return data?.split(',');
                }
                message.error(msg);
            }
            return [];
        }
    });

    // 获取通知模板
    const { data, loading, run: fetchTemplate } = useRequest(getNoticeTemplate, {
        manual: true,
        ...defaultFormatResult,
        onSuccess: res => {
            setDefaultTemplateValue(res?.templateContent || '');
            form.setFieldsValue({
                resourceRelation: transformFileList(res?.fileVOS || [])
            });
        }
    });

    // 获取默认模板内容
    const { loading: defaultContentLoading, run: fetchTemplateDefaultContent } = useRequest(
        () =>
            getNoticeTemplateDefaultContent({
                templateType: query?.type,
                templateCategory: 2,
                isDefault: 1
            }),
        {
            manual: true,
            ...defaultFormatResult,
            onSuccess: res => {
                const { rows = [] } = res;
                if (rows.length) {
                    setDefaultTemplateValue(rows[0]?.templateContent || '');
                }
            }
        }
    );

    const disabledList = React.useMemo(() => {
        if (!data) {
            return usedList;
        }
        if (usedList && data?.organizationCodes) {
            return usedList?.filter(item => data?.organizationCodes.indexOf(item) === -1);
        }
        return [];
    }, [JSON.stringify(usedList), JSON.stringify(data)]);

    // 保存面试评估表
    const { loading: saveLoading, run: saveTemplate } = useRequest(
        isAddPage ? addNoticeTemplate : updateNoticeTemplate,
        {
            manual: true,
            onSuccess: res => {
                const { code, msg } = res;
                if (code === 10000) {
                    message.success('操作成功');
                    pageTabUtil.goBack();
                    return;
                }
                message.error(msg);
            }
        }
    );
    /**
     * 富文本校验 false 不通过 true 通过
     */
    const isPassedRef = useRef(false);
    const [isPassed, setIsPassed] = useState(false);
    const getIsPassed = () => {
        console.log('getIsPassed，flag', flag);
        console.log('getIsPassed，editorValue', editorValue);
        isPassedRef.current =
            !flag ||
            (editorValue &&
                editorValue !== '<p></p>' &&
                editorValue !==
                    '<p size="0" _root="undefined" __ownerID="undefined" __hash="undefined" __altered="false"></p>');
        setIsPassed(isPassedRef.current);
        return isPassedRef.current;
    };
    useEffect(() => {
        getIsPassed();
    }, [flag, editorValue]);

    const validateText = () =>
        editorValue &&
        editorValue !== '<p></p>' &&
        editorValue !== '<p size="0" _root="undefined" __ownerID="undefined" __hash="undefined" __altered="false"></p>';

    const handleSubmit = () => {
        setFlag(true);
        if (!validateText()) {
            return;
        }
        form.validateFieldsAndScroll(async (err, values) => {
            if (!err) {
                const { resourceRelation, organizationCodes } = values;
                const isSingle = typeof organizationCodes === 'string';
                const newOrganizationCodes = isSingle ? [organizationCodes] : organizationCodes;
                const params = {
                    ...values,
                    templateContent: editorValue
                        .replace(/<span data-foo="/g, '${')
                        .replace(/" data-id="[0-9]+" class="column-item">[\u4e00-\u9fa5]+<\/span>/g, '}'),
                    resourceRelation: resourceRelation?.uploadResourceFile
                        ? [resourceRelation?.uploadResourceFile]
                        : [],
                    // eslint-disable-next-line no-nested-ternary
                    organizationCodes:
                        newOrganizationCodes && newOrganizationCodes.length > 0 ? newOrganizationCodes.join(',') : '',
                    organizationNames: data?.isDefault
                        ? data.organizationNames
                        : newOrganizationCodes?.map(o => gradeMap[o]?.organizationName).join(',') || ''
                };
                if (isAddPage) {
                    params.templateType = query?.type;
                    params.templateCategory = isOfferInfo ? 2 : 1;
                } else {
                    params.id = query?.id;
                }
                saveTemplate(params);
            }
        });
    };

    const handleChange = React.useCallback(html => {
        // console.log(html);
        setEditorValue(html);
        if (!flag && html && html !== '<p></p>') {
            setFlag(true);
        }
    }, []);

    React.useEffect(() => {
        if ([TEMPLATE_TYPE.OFFER, TEMPLATE_TYPE.BACKGROUND, TEMPLATE_TYPE.OFFER_INFO].includes(query?.type)) {
            fetchOrgList();
            fetchUsedList();
        }
        if ([TEMPLATE_TYPE.OFFER_INFO].includes(query.type) && isAddPage) {
            fetchTemplateDefaultContent();
        }
        if (query?.id) {
            fetchTemplate(query?.id);
        }
    }, [query]);

    return (
        <PageHeaderWrapper>
            <Card
                title={
                    isAddPage
                        ? `添加${TEMPLATE_TITLE[query?.type] || '通知'}模板`
                        : `编辑${TEMPLATE_TITLE[query?.type] || '通知'}模板`
                }
                bordered={false}
                loading={loading}
                extra={
                    <BottomAction>
                        <Button onClick={() => pageTabUtil.goBack()} style={{ marginRight: 8 }}>
                            取消
                        </Button>
                        <Button type="primary" onClick={handleSubmit} loading={saveLoading}>
                            保存
                        </Button>
                    </BottomAction>
                }
            >
                <Form className={styles.formWrap} style={{ marginTop: 24 }}>
                    <Form.Item label="模板名称">
                        {getFieldDecorator('templateName', {
                            initialValue: data?.templateName || '',
                            rules: [
                                {
                                    required: true,
                                    message: '请输入模板名称'
                                }
                            ]
                        })(<Input placeholder="请输入模板名称" allowClear maxLength={20} />)}
                    </Form.Item>
                    {!isOfferInfo && (
                        <Form.Item label="邮件主题">
                            {getFieldDecorator('templateTitle', {
                                initialValue: data?.templateTitle || '',
                                rules: [
                                    {
                                        required: true,
                                        message: '请输入邮件主题'
                                    }
                                ]
                            })(<Input placeholder="请输入邮件主题" allowClear maxLength={50} />)}
                        </Form.Item>
                    )}
                    <Form.Item label="适用行政机构">
                        {data?.isDefault === 1 && '全集团'}
                        {data?.isDefault === 1 &&
                            form.getFieldDecorator('organizationCodes', {
                                initialValue:
                                    (isOfferInfo ? data?.organizationCodes : data?.organizationCodes?.split(',')) ||
                                    undefined
                            })(<input type="hidden" />)}
                        {data?.isDefault !== 1 &&
                            [TEMPLATE_TYPE.OFFER, TEMPLATE_TYPE.BACKGROUND, TEMPLATE_TYPE.OFFER_INFO].includes(
                                query?.type
                            ) && (
                                <Spin spinning={orgLoading || usedLoading}>
                                    {getFieldDecorator('organizationCodes', {
                                        initialValue:
                                            (isOfferInfo
                                                ? data?.organizationCodes
                                                : data?.organizationCodes?.split(',')) || undefined,
                                        rules: [
                                            {
                                                required: true,
                                                message: '请选择行政机构'
                                            }
                                        ]
                                    })(
                                        <CompanySelect
                                            treeCheckable={!isOfferInfo}
                                            dataSource={orgList || []}
                                            disabledKeys={disabledList}
                                        />
                                    )}
                                </Spin>
                            )}
                    </Form.Item>
                    <Form.Item
                        label={contentTittle}
                        help={isPassed ? '' : `${contentTittle}不能为空`}
                        validateStatus={isPassed ? '' : 'error'}
                        required
                    >
                        <Spin spinning={defaultContentLoading}>
                            <BraftTemplate
                                type={query?.type}
                                onBlur={() => setFlag(true)}
                                onChange={handleChange}
                                initialValue={data?.templateContent || defaultTemplateValue || ''}
                            />
                        </Spin>
                    </Form.Item>
                    {!isOfferInfo && (
                        <Form.Item label="邮件附件">
                            {getFieldDecorator('resourceRelation')(
                                <FileUpload
                                    checkFileSizeMsg="文件大小不能超过10MB！"
                                    checkFileSize={10}
                                    categoryCode="RecruitMessageTemplateFile"
                                    checkFileType="DOC,DOCX,PDF,JPG,JPEG,rar,zip"
                                    checkFileTypeMsg="附件格式不合规，请确认！"
                                >
                                    <Button
                                        disabled={form.getFieldValue('resourceRelation')?.allFileList?.length > 4}
                                        style={{ marginTop: 4, marginBottom: 4 }}
                                    >
                                        添加附件
                                    </Button>
                                    <div onClick={e => e.stopPropagation()}>
                                        {/* 支持扩展名：.rar .zip .doc .docx .pdf .jpg... */}
                                        支持 pdf、doc、docx、jpg、jpeg、rar、zip 等格式的附件，单个文件大小为10MB以内
                                    </div>
                                </FileUpload>
                            )}
                        </Form.Item>
                    )}
                </Form>
            </Card>
        </PageHeaderWrapper>
    );
};

export default Form.create({})(NoticeTemplateEdit);
